<template>
    <a-layout class="layout">
        <a-layout-header >
            <a-row justify="space-between">
                <a-col :span="8">
                    <router-link  to="/">回到首页</router-link>
                </a-col>
                <a-col v-if="utils.isEmpty(userStore.user.id)">
                    <a-space>
                            <a-button type="link" @click="showModal">登录</a-button>
                            <router-link to="/register">注册</router-link>
                    </a-space>
                </a-col>
                <a-col v-else >
                    <a-space>
                        <a-avatar
                            size="large"
                            shape="square"
                            :src="'data:image/jpeg;base64,'+userStore.user.base64Data">
                        </a-avatar>
                        <router-link to="/home">
                            <span>欢迎，{{userStore.user.nickname}}</span>
                        </router-link>
                        <router-link to="/home?tab=3">
                            <a-badge :count="notificationCount"
                                     :number-style="{
                                      backgroundColor: '#52c41a',
                                      boxShadow: '0 0 0 1px #d9d9d9 inset',
                                    }"/>
                        </router-link>
                        <a-button type="link" @click="logout">退出</a-button>
                    </a-space>
                </a-col>
            </a-row>
        </a-layout-header>
        <a-layout-content style="padding: 0 50px">

            <div :style="{ background: '#fff', padding: '24px', minHeight: '280px',marginTop:'15px' }">
                <router-view/>
            </div>
        </a-layout-content>
        <a-layout-footer style="text-align: center">
            Ant Design ©2018 Created by Ant UED
        </a-layout-footer>
    </a-layout>

    <a-modal v-model:open="openLoginModel" title="登录" @ok="handleOk">
        <a-form
            :model="loginUserForm"
            name="basic"
            :label-col="{ span: 5 }"
            :wrapper-col="{ span: 16 }"
            autocomplete="off"
        >
            <a-form-item
                label="邮箱"
                name="email"
                :rules="[{ required: true, message: '输入邮箱!' }]"
            >
                <a-input v-model:value="loginUserForm.email" />
            </a-form-item>

            <a-form-item
                label="密码"
                name="password"
                :rules="[{ required: true, message: '输入密码!' }]"
            >
                <a-input-password v-model:value="loginUserForm.password" />
            </a-form-item>
        </a-form>
    </a-modal>
</template>
<script setup>
import { RouterLink, RouterView } from 'vue-router'
import {computed, onMounted, reactive, ref, watch} from "vue";
import axios from 'axios'
import { useUserStore } from './stores/user';
import utils from '@/utils/utils.js';
import { message } from 'ant-design-vue';

import { notification, Button } from 'ant-design-vue';
import { h } from 'vue';

const openLoginModel = ref(false)

const userStore  = useUserStore()
const handleOk = () =>{
    // console.log(loginUser.value)
    axios.get(`/user/login?email=${loginUserForm.email}&password=${loginUserForm.password}`).then(res => {
        if(res.data.success){
            message.success({
                content: () => '登录成功',
                style: {
                    marginTop: '20vh',
                },
            });
            let user_in = res.data.data
            // let jsonString = JSON.stringify(user);
            // console.log(jsonString)
            userStore.setUser(user_in)
            openLoginModel.value = false
        }else{
            alert(res.data.message)
        }
    })
}

const logout = ()=>{
    userStore.setUser({})
}
const showModal = ()=>{
    openLoginModel.value = true
}


const loginUserForm = reactive({
    email: '',
    password: '',
});

const notificationCount = ref(0)


const changeReadStatus = (id)=>{
    axios.put("/notice/update/status",{
        id:id,
        readStatus:'Read'
    }).then(res => {
        console.log("更新成功")
    })
}
const openNotification = (notice)=> {
    notificationCount.value += 1
    const key = `open${Date.now()}`;
    notification.open({
        message: '通知',
        description: notice.content,
        btn: () => h(Button, {
            type: 'primary',
            size: 'small',
            onClick: () => {
                notification.close(key)
                console.log("已读")
                changeReadStatus(notice.id)
                notificationCount.value -= 1
            }

        }, {
            default: () => '已阅',
        }),
        key,
    });
}

const openws = ()=>{
    let ws = new WebSocket('ws://localhost:8088/notice/' + userStore.user.id);
    ws.onopen = function() {
        console.log("Connected to the chat server");
        // ws.send("Hello, server!");
    };

    ws.onmessage = event => {
        console.log("Received from chat server: " , event.data);
        let notice = JSON.parse(event.data)
        console.log(notice)
        openNotification(notice)
    };

    ws.onclose = function() {
        console.log("Disconnected from the server");
    };

    ws.onerror = function(event) {
        console.log("Error: " + event.data);
    };
}


watch(() =>userStore.user.id,(newid)=>{
    if(newid != null){
        openws();
    }
})



</script>

<style scoped>

#components-layout-demo-top .logo {
    float: left;
    width: 120px;
    height: 31px;
    margin: 16px 24px 16px 0;
    background: rgba(255, 255, 255, 0.3);
}
.ant-row-rtl #components-layout-demo-top .logo {
    float: right;
    margin: 16px 0 16px 24px;
}

</style>